package com.mulanweb.api.module.controller.admin;

import com.jfinal.kit.StrKit;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.Photo;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.RandomStringGenerator;
import com.mulanweb.utils.StringFormatterUtil;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;
import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/9/18.
 */
@ValidateFile
public class PhotoController extends BaseController {

    @ValidateForm
    public void update() throws IOException{
        String imgName = RandomStringGenerator.getRandomStringByLength(5) + super.getFile().getFileName();
        Integer typeId = getParaToInt("typeId");
        Long targetId = getParaToLong("targetId");
        List<String> deletePaths = new ArrayList<>();
        boolean tag = true;
        if (typeId == 14 || typeId == 16) {
            Photo photo = Photo.dao.findFirst("SELECT * FROM photo WHERE type_id =? AND target_id=?", typeId, targetId);
            if(photo !=null ){
                String fileName = photo.getPath();
                if (photo.delete()) {
                    deletePaths.add(fileName);
                } else {
                    tag = false;
                }
            }
        }
        for (String fileName : deletePaths) {
            File file = new File(Constant.ContextPatameter.PHOTO_SAVE_PATH + fileName);
            if (file.exists() && file.isFile()) {
                file.delete();
            } else {
                //todo 记录错误信息到数据库（本地文件删除失败，文件名为fileName）
                //tag = false;
            }
        }

        if (tag) {
            imgName = StringFormatterUtil.removeKeyWord(imgName);
            Photo photoTest = Photo.dao.findFirst("SELECT * FROM photo WHERE path=?", imgName);
            int i = 0;
            while (StrKit.notNull(photoTest) && photoTest.getPath() == imgName) {//判断是否重名
                imgName = imgName + "_" + i;
                photoTest = Photo.dao.findFirst("SELECT * FROM photo WHERE path=?", imgName);
                i++;
            }
            if (super.getFile().getFile().renameTo(new File(Constant.ContextPatameter.PHOTO_SAVE_PATH + imgName))) {
                if(typeId == 14){
                    Thumbnails.of("D:/website/mulan_xxl/static/view-img/"+imgName)
                            .size(240, 160)
                            .toFile("D:/website/mulan_xxl/static/thumbnail/"+imgName) ;
                }
                Photo photo = new Photo();
                photo.setPath(imgName);
                photo.setTargetId(targetId);
                photo.setTypeId(typeId);
                photo.setCreateTime(new Date());
                if (photo.save()) {
                    returnSuccessJson();
                } else {
                    returnFailureJson();
                }
            }else{
                System.out.println("----------------------保存图片失败");
            }
        }else{
            System.out.println("----------------------保存图片失败**2");
        }
    }

    @ValidateForm
    public void save() throws IOException{
        String imgName = RandomStringGenerator.getRandomStringByLength(5) + super.getFile().getFileName();
        imgName = StringFormatterUtil.removeKeyWord(imgName);
        Photo photoTest = Photo.dao.findFirst("SELECT * FROM photo WHERE path=?", imgName);
        int i = 0;
        while (StrKit.notNull(photoTest)) {//判断是否重名
            imgName = imgName + "_" + i;
            photoTest = Photo.dao.findFirst("SELECT * FROM photo WHERE path=?", imgName);
            i++;
        }
        if (super.getFile().getFile().renameTo(new File( Constant.ContextPatameter.PHOTO_SAVE_PATH+ imgName))) {
            Long targetId = getParaToLong("targetId");
            Integer typeId = getParaToInt("typeId");
            if(typeId == 14 || typeId == 18){
                Thumbnails.of("D:/website/mulan_xxl/static/view-img/"+imgName)
                        .size(240, 160)
                        .toFile("D:/website/mulan_xxl/static/thumbnail/"+imgName) ;
            }
            Integer[] tt = {13, 14, 15, 16,17,18};
            boolean typeError = false;
            for (int t : tt) {
                if (t == typeId) {
                    typeError = true;
                    break;
                }
            }
            if (!typeError) {
                returnJson(0, "照片类型错误");
                return;
            }
            Photo photo = new Photo();
            photo.setPath(imgName);
            photo.setTargetId(targetId);
            photo.setTypeId(typeId);
            photo.setCreateTime(new Date());
            if (photo.save()) {
                returnSuccessJson();
            } else {
                returnFailureJson();
            }
        }

   /*     super.getFile().getFile().renameTo(new File(super.getRequest().getContextPath()+ super.getFile().getFileName()));
        System.out.println(super.getFiles().size());
        try {
            InputStream is = super.getRequest().getInputStream();
            if (null != is) {
                IOUtils.copy(is, new FileOutputStream(new File("D:\\tt1.jpg")));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(super.getFiles().size());

        if(super.getFile()==null && StrKit.isBlank(super.getPara("targetId"))){
            returnJson(0,"系统异常");
            return;
        }*/
    }

    @ValidateForm
    public void delete(){
        Long photoId = getParaToLong("photoId");
        Photo photo = Photo.dao.findById(photoId);
        if(null == photo){
            returnFailureJson();
            return;
        }
        if(photo.delete()){
            File file = new File(Constant.ContextPatameter.PHOTO_SAVE_PATH + photo.getPath());
            if (file.exists() && file.isFile()) {
                file.delete();
            } else {
                //todo 记录错误信息到数据库（本地文件删除失败，文件名为fileName）
                //tag = false;
            }
            returnSuccessJson();
        }else{
            returnFailureJson();
        }
    }

    public void getPhotoList(){
        Long targetId = getParaToLong("targetId");
        Long typeId = getParaToLong("typeId");
        Integer typeId2 = null;
        if (typeId == 13) {
            typeId2 = 14;
        }else if(typeId == 17){
            typeId2 = 18;
        } else {
            typeId2 = 16;
        }
        List<Photo> photos = Photo.dao.find("select * from photo where (type_id = ? OR type_id = ?) AND target_id = ? ORDER BY type_id DESC", typeId, typeId2, targetId);
        returnSuccessJson(photos);
    }

    public void saveDetail() throws IOException {
        String imgName = RandomStringGenerator.getRandomStringByLength(5) + super.getFile().getFileName();
        imgName = StringFormatterUtil.removeKeyWord(imgName);
        String path = "D:\\website\\mulan_xxl\\static\\detail-img\\";
        File file = new File(path+imgName);
        int i = 0;
        while (file.exists()) {//判断是否重名
            imgName = imgName + "_" + i;
            file = new File(path+imgName);
            i++;
        }
        if (super.getFile().getFile().renameTo(new File(path + imgName))) {
            renderText("{\"error\":0,\"url\":\"http://weixin.mulanweb.com/static/detail-img/"+imgName+"\"}");
        }else{
            returnFailureJson();
        }
    }
}
